package com.ruoyi.common.core.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerifyCodeUtils {
    private static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static final int CODE_LENGTH = 4;
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;

    public static String generateVerifyCode(int length) {
        Random rand = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(VERIFY_CODES.charAt(rand.nextInt(VERIFY_CODES.length())));
        }
        return sb.toString();
    }

    public static BufferedImage createImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, WIDTH, HEIGHT);
        g2.setFont(new Font("Arial", Font.BOLD, 28));
        Random rand = new Random();
        for (int i = 0; i < code.length(); i++) {
            g2.setColor(new Color(rand.nextInt(150), rand.nextInt(150), rand.nextInt(150)));
            g2.drawString(String.valueOf(code.charAt(i)), 20 + i * 22, 30 + rand.nextInt(5));
        }
        // 干扰线
        g2.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < 8; i++) {
            int x1 = rand.nextInt(WIDTH);
            int y1 = rand.nextInt(HEIGHT);
            int x2 = rand.nextInt(WIDTH);
            int y2 = rand.nextInt(HEIGHT);
            g2.drawLine(x1, y1, x2, y2);
        }
        g2.dispose();
        return image;
    }
}